/* *
 * ECSHOP 系统统一处理js
 * @author : 何俊(azj1001@sina.com)
 * @version : v1.0
 */
var Browser = new Object();
Browser.isMozilla = (typeof document.implementation != 'undefined')
		&& (typeof document.implementation.createDocument != 'undefined')
		&& (typeof HTMLDocument != 'undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != -1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
var Dmlx = {
	commonSymbol:"[\\,\\`\\~\\!\\@\\#\\$\\%\\\\\^\\&\\*\\(\\)\\-\\_\\=\\+\\[\\{\\]\\}\\\\\|\\;\\:\\‘\\’\\“\\”\\<\\>\\/?]+"
	,sex : [ {
		id : 'M',
		text : '男'
	}, {
		id : 'F',
		text : '女'
	} ],
	_hFrozenColumns : [ {
		field : 'ck',
		checkbox : true
	}, {
		title : '唯一编号',
		field : 'uuid',
		width : 120,
		sortable : true,
		hidden : true,
		align : 'center',
		sortable : true
	} ],
	_hFrozenColumns_nocheck : [ {
		title : '唯一编号',
		field : 'uuid',
		width : 120,
		sortable : true,
		hidden : true,
		align : 'center',
		sortable : true
	} ],
	sort:{asc:0,desc:1}
};
var getDate=function(date){
	/* 基本信息内的选择框 */
	var y = date.getFullYear(),
	 m = date.getMonth() +1,
	 d = date.getDate();
	var date = y+ "/" + (m<10?'0'+m:m) + "/" + (d<10?'0'+d:d);
	return date;
}
var MyUtils = {
		 htmlEncode:function(text) {/** html编码 */return text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g,'&lt;').replace(/>/g, '&gt;');}
		,valueAlign:function(val,align){return '<div align="'+align+'">' + val +'</div>';}
		,trim:function(text) {if (typeof (text) == "string") {return text.replace(/^\s*|\s*$/g, "");} else {return text;}}
	    ,isEmpty:function(val) {
	    	switch (typeof (val)) {
	    	case 'string':
	    		return MyUtils.trim(val).length == 0 ? true : false;
	    		break;
	    	case 'number':
	    		return val == 0;
	    		break;
	    	case 'object':
	    		return val == null;
	    		break;
	    	case 'array':
	    		return val.length == 0;
	    		break;
	    	default:
	    		return true;
	    	}
	    }
	    ,isNumber:function(val) {var reg = /^[\d|\.|,]+$/;return reg.test(val);}
	    ,isInt:function(val) {if (val == "") {return false;}var reg = /\D+/;return !reg.test(val);}
		,isEmail:function(email) {var reg1 = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/;return reg1.test(email);}
		,isTel:function(tel) {var reg = /^[\d|\-|\s|\_]+$/; /*只允许使用数字-空格等*/return reg.test(tel);}
		,isSameWord:function (words) {
			var firstTmp="";
			if (words != null && words != "") {
				firstTmp = words.charAt(0);
			}
			var patternTmp = "[" + firstTmp + "]{" + (words.length) + "}";
			var pattern = new RegExp(patternTmp);
			return pattern.test(words);
		}
		,findSexName:function(val) {
			if (val) {
				for ( var rcd in Dmlx.sex) {
					if (rcd.id == val.toUpperCase()) {
						return rcd.text;
					}
				}
			}
			return val;
		}
		,sendPost:function(url, datas, callback) {
			$.post(url, datas, function(msg) {
				try {
					callback(msg);
				} catch (e) {
					var f = "操作失败!" + "  [" + e + "]";
					alert(f);
				}
			});
		}
		,toJsonObject:function(str) {return JSON.parse(str);}
		,toJsonStr:function(json) {return JSON.stringify(json);}
		,MD5:function(val) {return $.md5(val);}
		,check_pwd_by_name:function(password, uname) {
			function checkWords(password, userName) {
				if (userName == undefined) {
					return false;
				}
				if (userName.substring(0, userName.length - 1) == password) {
					return true;
				}
				if (userName.substring(0, userName.length - 1) == password.substring(0,
						password.length - 1)) {
					return true;
				}
				if (userName.substring(1, userName.length) == password) {
					return true;
				}
				if (userName.substring(1, userName.length) == password.substring(1,
						password.legnth)) {
					return true;
				}
				if (password.substring(0, password.length - 1) == userName) {
					return true;
				}
				if (password.substring(1, password.length) == userName) {
					return true;
				}
			}

			function check(password, uname) {
				if (MyUtils.isEmpty(password)) {
					return 1; // 密码为空
				}
				if (password.length > 20) {
					return 2; // 密码长度超过20
				}
				if (password.length < 6) {
					return 3; // 密码长度小于6
				}
				var pattern = /\s+/;
				if (pattern.test(password)) {
					return 4; // 密码中包含空格
				}
				var isAllNumPattern = /^[0-9]+$/;
				if (isAllNumPattern.test(password)) {
					return 5; // 密码全由数字组成
				}

				var isALLCharPattern = /^[a-zA-Z]+$/;
				if (isALLCharPattern.test(password)) {
					return 6; // 密码全由字母组成
				}

				var isAllSpecial = /^[^0-9A-Za-z]+$/;
				if (isAllSpecial.test(password)) {
					return 7; // 密码全由特殊字符组成
				}

				if (MyUtils.isSameWord(password)) {
					return 8; // 密码都是由相同字母或数字组成
				}

				if (checkWords(password, uname)) {
					return 9; // 密码和用户名相似
				}

				var numPattern = "d*" + Dmlx.commonSymbol + "";
				var allPattern = "\\\d+[A-Za-z]|[A-Za-z]+[0-9]+|[A-Za-z]+"
						+ Dmlx.commonSymbol + "[0-9]+|[A-Za-z]+[0-9]+" + Dmlx.commonSymbol + "|"
						+ numPattern + "";
				var allReg = new RegExp(allPattern);
				if (!allReg.test(password)) {
					return 10; // 密码不符合 字母+数字 或 字符+数字 或 字母+字符 或 字母+字符+数字
				}
				return 0;
			}
			var error = check(password, uname);
			var msg = null;
			if (error == 1) {
				msg = ("密码不能为空");
			} else if (error == 2) {
				msg = ("密码为6-20位字符");
			} else if (error == 3) {
				msg = ("密码为6-20位字符");
			} else if (error == 4) {
				msg = ("密码中不允许有空格");
			} else if (error == 5) {
				msg = ("密码不能全为数字");
			} else if (error == 6) {
				msg = ("密码不能全为字母，请包含至少1个数字或符号 ");
			} else if (error == 7) {
				msg = ("密码不能全为符号");
			} else if (error == 8) {
				msg = ("密码不能全为相同字符或数字");
			} else if (error == 9) {
				msg = ("密码与用户名相似，为了您的账户安全请重新输入");
			} 
			return {error:error,msg:msg};
		}
		,createPaginPanelWithQueryparams:function(divId, url, frozenColumns,columns, toolbar, onDblClickRow, title, queryParams) {
			try {
				$('#' + divId).datagrid(
						{
							iconCls : 'icon-save',
							title : MyUtils.valueAlign(title,"left"),
							fit : true,
							nowrap : false,
							striped : true,
							collapsible : true,
							url : url,
							remoteSort : true,
							idField : 'uuid',
							method : 'POST',
							singleSelect : false,
							pageSize : 20,
							pageList : [ 10, 15, 20 ],
							pageNumber : 1,
							rownumbers : true,
							pagination : true,
							loadMsg : '正在加载信息,请稍等...',
							frozenColumns : [ frozenColumns ],
							columns : [ columns ],
							rownumbers : false,
							onDblClickRow : function(rowIndex, row) {
								if (onDblClickRow != null) {
									onDblClickRow(rowIndex, row);
								}
							},
							queryParams : queryParams,
							toolbar : (null == toolbar || !toolbar
									|| toolbar.length == 0 ? null : toolbar)
						});
			} catch (e) {
				if (e.name == 'ReferenceError') {
					$.messager.alert("系统提示", MyUtils.valueAlign("操作方法不存在" + "[" + e + "]","left"), "waring");
				} else {
					showJsException(e,"数据加载失败!");
				}
			}
		}
		,openMask:function(loadMsg, obj) {$('<div class="datagrid-mask-msg" style="display: block;"></div>').html(loadMsg).appendTo(obj);}
		,hiddenMask:function(obj) {obj.children("div.datagrid-mask-msg").remove();}
		,setMaskPosition:function(obj) {obj.children("div.datagrid-mask-msg").css({left:$(obj).offset().left,top:$(obj).offset().top});}
		,createQueryConditionBean:function(col, symbol, replace, val, alis) {
			var query = '';
			query = '{' + '"col":"' + (col ? col : "null") + '"' + ',"symbol":"'
					+ (symbol ? symbol : "=") + '"' + ',"replace":"'
					+ (replace ? replace : "?") + '"' + ',"val":"'
					+ (val ? val : "null") + '"' + ',"alis":"' + (alis ? alis : "null")
					+ '"' + '}';
			return query;
		}
		,createQueryConditionBean:function(col, symbol, replace, val, alis,
				type) {
			var query = '';
			query = '{' + '"col":"' + (col ? col : "null") + '"' + ',"symbol":"'
					+ (symbol ? symbol : "=") + '"' + ',"replace":"'
					+ (replace ? replace : "?") + '"' + ',"val":"'
					+ (val ? val : "null") + '"' + ',"alis":"' + (alis ? alis : "null")
					+ '"' + ',"type":"' + (type ? type : "0") + '"' + '}';
			return query;
		}
		,_getChineseBytes:function(str) {/** 获取包含中文字符的字符串的字节：一个中文转换成2个xx串 */return str.replace(/[\u4E00-\u9FA5\uF900-\uFA2D]/ig, "xx");}
		,_chineseLengthTooLong:function(str, name, length) {
			var len = _getChineseBytes(str).length;
			if (len > length) {
				var msg = name + _field_long;
				msg = msg.replace('x', length);
				msg = msg.replace('y', len);
				return msg;
			}
			return null;
		}
		,_searchPanelData:function(panelId, url, params) {
			$('#' + panelId).datagrid({
				url : url,
				pageNumber : 1,
				queryParams : params
			});
		}
		,_getToolbarWin:function(frameId, tableId, openDiv, bindOKfunc, title,button) {
			if(button=='undefiend' || button==null) {
				button = '确定';
			}
			$('#' + tableId).remove();
			$('#_win').remove();

			var div = '<div id="_win" class="easyui-window" title="'
					+ title
					+ '" collapsible="false" minimizable="false" closed="false" closable="true"'
					+ 'maximizable="false" iconCls="icon-save">'
					+ '<div class="easyui-layout" fit="true">'
					+ '<div id="_twin" region="center" border="false" style="padding: 10px; background: #fff; border: 1px solid #ccc;">'
					+ '</div>'
					+ '<div region="south" border="false" style="text-align: right; height: 30px; line-height: 30px;">'
					+ '<a id="btnEp" icon="icon-ok" style="margin-right:20px;" href="javascript:void(0)">'+button+'</a> '
					+ '</div> </div>';

			$('#' + frameId).append(div);
			$('#btnEp').linkbutton({
				plain : true
			});

			$(openDiv).appendTo($('#_twin'));
			$('#btnEp').unbind('click');
			$('#btnEp').bind('click', bindOKfunc);
			return $('#_win');
		}
		,_formartInfoText:function(value, maxIndex) {
			var index = MyUtils._getChineseBytes(value).length;
			var str = '';
			if (index > maxIndex) {
				str = value.substring(0, maxIndex);
				if (str.length < maxIndex) {
					return str;
				} else {
					return str + '...';
				}
			}
			return value;
		}
		,getDate:function(date){
			/* 基本信息内的选择框 */
			var y = date.getFullYear(),
			 m = date.getMonth() +1,
			 d = date.getDate();
			var date = y+ "/" + (m<10?'0'+m:m) + "/" + (d<10?'0'+d:d);
			return date;
		}
		,createChineseDatebox:function (obj) {
			$('#' + obj).datebox({
				showSeconds:false 
			   ,currentText:''
			   ,closeText:'关闭'
			   ,formatter:function(date){
				   return getDate(date);
				}
			}).datebox("calendar").calendar({
				  months : [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月","九月", "十月", "十一月", "十二月" ]
			 	 ,weeks : ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
			});
		}
		,waring:function(msg){
			$.messager.alert(_msg_sys, MyUtils.valueAlign(msg,"left"), "warning");
		}
		,error:function(msg){
			$.messager.alert(_msg_sys, MyUtils.valueAlign(msg,"left"), "error");
		}
		,info:function(msg){
			$.messager.alert(_msg_sys, MyUtils.valueAlign(msg,"left"), "info");
		}
};

var showJsException = function(e,msg) {
	if(msg =='undefiend'||msg == null ) {
		msg = _msg_js_error;
	}
	var es = e.toString();
	if(es.indexOf("ReferenceError: ") != -1) {
		es = es.substring("ReferenceError: ".length,es.indexOf("is not defined"));
	}
	if(Browser.isFirefox){
		var errorLine = e.lineNumber;
		var file = e.fileName;
		if(file) {
			file = file.substring(file.lastIndexOf("/") + 1);
		}
		es = "文件[" + file + "] 第 [" + errorLine + "] 行 未发现[" + es + "] 对象"; 
	} else {
		es = " 未发现[" + es + "] 对象"; 
	}
	if(showJsError) {
		$.messager.alert(_msg_sys, MyUtils.valueAlign(msg + " ：" + es + "","left"), "warning");
	} else {
		$.messager.alert(_msg_sys, MyUtils.valueAlign(msg,"left"), "warning");
	}
};

var datagridOneRow = function(id){
	var rows = $('#' + id).datagrid("getSelections");
	if(rows.length != 1) {
		MyUtils.waring(_single_select);
		return null;
	}
	var record =rows[0];
	return record; 
};
